package com.dearcocoa.service.impl;

import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.dearcocoa.common.UserPrincipal;
import com.dearcocoa.entity.*;
import com.dearcocoa.mapper.*;
import lombok.Builder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>
 *自定义UserDetails查询
 * </p>
 *
 * @Package: com.dearcocoa.service.impl
 * @ClassName: CustomUserDetailsService
 * @Author: shengong
 * @Date: Created in 2020-07-25 15:44
 * @Version: V1.0
 * @Description: TODO
 */
@Service
public class CustomUserDetailsService implements UserDetailsService {

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private RoleMapper roleMapper;

    @Autowired
    private PermissionMapper permissionMapper;

    @Autowired
    private UserRoleMapper userRoleMapper;

    @Autowired
    private RolePermissionMapper rolePermissionMapper;

    @Override
    public UserDetails loadUserByUsername(String usernameOrEmailOrPhone) throws UsernameNotFoundException {
        User user = userMapper.findByUsernameOrEmailOrPhone(usernameOrEmailOrPhone);
        if (user == null) {
            throw new UsernameNotFoundException("未找到用户信息：" + usernameOrEmailOrPhone);
        }
        List<UserRole> userRoles = userRoleMapper.selectList(Wrappers.lambdaQuery(new UserRole().setUserId(user.getId())));
        List<Long> roleIds = userRoles.stream().
                map(UserRole::getRoleId).
                collect(Collectors.toList());
        List<Role> roles = roleMapper.selectList(Wrappers.<Role>lambdaQuery().in(Role::getId, roleIds));
        List<RolePermission> rolePermissions = rolePermissionMapper.selectList(Wrappers.<RolePermission>lambdaQuery().in(RolePermission::getRoleId, roleIds));
        List<Long> permissionIds = rolePermissions.stream().
                map(RolePermission::getPermissionId).
                collect(Collectors.toList());
        List<Permission> permissions = permissionMapper.selectList(Wrappers.<Permission>lambdaQuery().in(Permission::getId, permissionIds));
        return UserPrincipal.create(user, roles, permissions);
    }
}
